import WebHeader from '@/www/components/WebHeader'
import WebFooter from '@/www/components/WebFooter'
import { getQuote, uploadFile, postQuoteOrder } from '@/apiv2/quote'
import yun from '@/utils/yun'
import { elt } from 'codemirror/src/util/dom'

const CODE = 'Sticker'

export default {
  components: { WebHeader, WebFooter },
  data() {
    return {
      quoteData: undefined,
      laminationDisable: undefined,
      checkValue: {
        flagLamination: false,//覆膜
        flagPressLine: false,//压线
        flagPlastic: false,//过塑
        flagFoldedPage: false,//折页
        flagCode: false,//打码
        flagPinholeLine: false,//针孔线
        flagPerforation: false,//打孔
        flagRound: false,//圆角
      },

      gramList: undefined,

      selectedCategory: undefined,

      quoteValue: {
        category: undefined,
        customQuantity: undefined,
        style: 1,
        quantity: undefined,
        size: undefined,
        customLength: undefined,
        customWidth: undefined,
        lamination: '',
        process: undefined,
      },

      processSelectOptions: {

      },

      customSize:false,
      user: undefined,
      quote: undefined,
      quoteList: undefined,
      detail: undefined,
      fileList: [],
      postData: {
        quantity: undefined,
        detail: undefined,
        amount: undefined,
        fileIds: undefined
      },
      note: undefined
    }
  },

  created(){
    const user = JSON.parse(localStorage.getItem('user'))
    this.user = user

    getQuote(CODE).then(res => {
      let quoteData = res.config
      this.selectedCategory = quoteData.cateData.list[0]
      this.quoteValue.category = this.selectedCategory.name
      this.quoteValue.quantity = this.selectedCategory.quantityList[0].name

      if(this.selectedCategory.canCut){
        this.quoteValue.process = 'cut'
      }else if(this.selectedCategory.canBeer){
        this.quoteValue.process = 'beer'
      }

      this.quoteValue.size = quoteData.sizeData.list[0].name
      this.quoteData = quoteData
    })
  },

  methods: {

    onCategoryChange(){
      this.quoteData.cateData.list.forEach(item => {
        if(item.name == this.quoteValue.category){
          this.selectedCategory = item
          if(this.selectedCategory.canCut){
            this.quoteValue.process = 'cut'
          }else if(this.selectedCategory.canBeer){
            this.quoteValue.process = 'beer'
          }
          this.quoteValue.lamination = ''
        }
      })
    },

    getA3Price(category,color,gram,rate){
      let cateList = this.quoteData.cateData.list
      let price = 0
      cateList.forEach(item => {
        if(item.name == category){
          item.gramList.forEach(sitem => {
            if(gram == sitem.gram){
              price = parseFloat(item[color + 'Price']) * parseFloat(rate) + parseFloat(sitem.price)
            }
          })
          return price
        }
      })
      return price
    },

    getQuantityCountArr(finalQantity){
      let category = this.selectedCategory
      let index = undefined
      let target = parseInt(finalQantity)
      let farr = []
      for(let i=(category.quantityList.length-1);i > -1;i--){
        let itemQuantity = parseInt(category.quantityList[i].name)
        if(target < itemQuantity){
          continue
        }
        if(!index){
          index = i
        }
        let m = target % itemQuantity
        farr.push({
          quantity: category.quantityList[i].name,
          count: parseInt(target / itemQuantity)
        })
        if(m == 0){
          break
        }else{
          target = m
        }
      }
      return farr
    },

    getQuote(){
      let detail = ''

      let {customSize,quoteData,selectedCategory,quoteValue,postData} = this

      if(customSize && (!quoteValue.customLength || !quoteValue.customWidth)){
        this.$message.error('请输入自定义尺寸')
        return
      }
      let {length,width} = this.getFinalSize()

      const CUSTOM_SIZE = length + '*' + width
      console.log('尺寸=' + CUSTOM_SIZE)

      let finalQantity = parseInt(quoteValue.customQuantity ? quoteValue.customQuantity : quoteValue.quantity) * parseInt(quoteValue.style)
      console.log('数量=' + finalQantity)

      const SQUARE = parseFloat(length) * parseFloat(width) / 1000000
      console.log('单张平方米=' + SQUARE)

      let isNormalSize = false
      for(let i = 0; i< quoteData.sizeData.list.length; i++){
        let item = quoteData.sizeData.list[i]
        if(CUSTOM_SIZE == item.name){
          isNormalSize = true
          break
        }
      }
      console.log('常规尺寸=' + isNormalSize)

      let quantityCountArr = this.getQuantityCountArr(finalQantity)
      console.log('数量阶梯组合：')
      console.log(quantityCountArr)

      let key = quoteValue.process + quoteValue.lamination
      console.log('取值KEY=' + key)

      let materialAmount = 0

      quantityCountArr.forEach(item => {
        let qty = parseInt(item.quantity)
        let cnt = parseInt(item.count)
        for(let i=(selectedCategory.quantityList.length-1);i > -1;i--){
          let item = selectedCategory.quantityList[i]
          if(qty == parseInt(item.name)){
            console.log('match')
            let price = 0
            if(isNormalSize){
              for(let j = 0; j < item.sizeList.length; j++){
                if(CUSTOM_SIZE == item.sizeList[j].name){
                  console.log('1')
                  price = item.sizeList[j][key]
                }
              }
            }else{
              console.log('2')
              price = item[key]
            }
            console.log('组合数量=' + parseFloat(qty))
            console.log('组合计数=' + parseFloat(cnt))
            console.log('单价=' + parseFloat(price))
            materialAmount += SQUARE * parseFloat(price) * parseFloat(qty) * parseFloat(cnt)
          }
        }
      })

      let processAmount = 0

      let totalAmount = materialAmount.toFixed(2)

      let quoteList = [{
        materialAmount: materialAmount.toFixed(2),
        quantity: finalQantity,
        processAmount: processAmount.toFixed(2),
        totalAmount: totalAmount
      }]

      let defaultFlag = false
      postData.amount = totalAmount
      postData.detail = detail
      this.postData = postData
      this.quoteList = quoteList
    },


    //自定义尺寸切换
    onCustomSizeToggle(){
      this.quoteValue.customLength = undefined
      this.quoteValue.customWidth = undefined
    },

    selectQuantity(){
      if(this.quoteValue.quantity){
        this.quoteValue.customQuantity = undefined
      }
    },
    customQuantity(){
      if(this.quoteValue.customQuantity){
        this.quoteValue.quantity = undefined
      }else{
        this.quoteValue.quantity = this.quoteData.stepData.list[0]
      }
    },

    syncCheck(name,target){
      if(this.checkValue[name]){
        this.checkValue[target] = true
      }
    },

    offCheck(name,target){
      if(!this.checkValue[name]){
        this.checkValue[target] = false
      }
    },

    submitOrder(){
      const {fileList,postData} = this

      if(fileList.length < 1){
        this.$message.error('请上传设计稿')
        return
      }

      let fileIds = [];
      fileList.forEach(item => {
        fileIds.push(item.id)
      })
      postData.fileIds = fileIds

      const loading = this.$loading({
        lock: true,
        text: '正在创建订单',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      });

      postQuoteOrder(postData).then(res => {
        loading.close()
        this.$message.success('成功创建订单')
        this.$router.push({
          path: '/submitOrder',
          query: { id : res.id}
        })
      }).catch(err => {
        loading.close()
        this.$message.error('创建订单失败')
      })
    },

    handleUpload: async function(data){
      const formData = new FormData()
      formData.append('file', data.file)
      const res = await uploadFile(formData)
      let fileList = this.fileList
      fileList.push(res.file)
      this.fileList = fileList
      console.log(fileList)
    },

    //获取最终尺寸
    getFinalSize(){
      let {quoteValue,customSize} = this
      let length = undefined
      let width = undefined
      if(quoteValue.customLength && quoteValue.customWidth && customSize){
        length = parseInt(quoteValue.customLength)
        width = parseInt(quoteValue.customWidth)
      }else if(quoteValue.size){
        let sizeStr = quoteValue.size.match(/\d+\*\d+/)[0]
        length = parseInt(sizeStr.split('*')[0])
        width = parseInt(sizeStr.split('*')[1])
      }
      return {
        length: length,
        width: width
      }
    },

  }
}
